<?php
class ControllerDelimanNhanvien extends Controller
{
	private $error = array();
	
   	function __construct() 
	{
		$listchek = $this->getListCheck();
		
		if(in_array($this->getMethod(),$listchek))
		{
			if(!$this->user->hasPermission($this->getRoute(), $this->getMethod()))
			{
				$this->response->redirect("?route=common/permission");
			}
		}
		$this->data['list_button'] = array();
		foreach($listchek as $method)
		{
			$this->data['list_button'][$method] = $this->user->hasPermission($this->getRoute(), $method);
		}
		
		$this->load->model("common/control");
		$this->load->model("core/user");
	 	$this->load->model("deliman/nhanvien");
		$this->load->model("deliman/khuvuc");
		$this->data['khuvucs'] = array();
		$this->model_deliman_khuvuc->getTree(0, $this->data['khuvucs']);
   	}
	
	public function index()
	{
		$this->getList();
	}
	
	public function insert()
	{
    	$this->getForm();
	}
	
	public function update()
	{	
		$this->data['haspass'] = false;
		$this->data['readonly'] = 'readonly="readonly"';
		$this->data['class'] = 'readonly';	
		$this->getForm();
		
		
  	}
	
	public function delete() 
	{
		$listnhanvienid=$this->request->post['delete'];
		if(count($listnhanvienid))
		{
			foreach($listnhanvienid as $nhanvienid)
			{
				$this->model_deliman_nhanvien->delete($nhanvienid);	
			}
			$this->data['output'] = "true";
		}
		$this->id="content";
		$this->template="common/output.tpl";
		$this->render();
  	}
	
	private function getList() 
	{
		$this->load->model("deliman/loainhanvien");
		$this->data['insert'] = $this->url->http('deliman/nhanvien/insert');
		$this->data['delete'] = $this->url->http('deliman/nhanvien/delete');	
		$loainhanviens = $this->model_deliman_loainhanvien->getList();
		
		$this->data['cbloainhanvien'] = $this->model_common_control->getDataCombobox($loainhanviens,"tenloainhanvien","loainhanvienid");
		
		$data = $this->request->get;
		$where ="";
		if($data['hoten']!="")
		{
			$where.=" AND hoten like '%".urldecode($data['hoten'])."%'";
		}
		if($data['loainhanvienid']!="")
		{
			$where.=" AND loainhanvienid like '%".$data['loainhanvienid']."%'";
		}
		if($data['khuvucphutrach']!="")
		{
			$data_khuvucid = array();
			$this->model_deliman_khuvuc->getTree($data['khuvucphutrach'], $data_khuvucid);
			$data_khuvucid = $this->string->matrixToArray($data_khuvucid,'khuvucid');
			$data_khuvucid = array_unique($data_khuvucid);
			$wherephutrach .= " AND khuvucid in ('".implode("','",$data_khuvucid)."')";
			
			//$wherephutrach = " AND khuvucid = '".$data['khuvucphutrach']."'";
			$wherephutrach .= " AND tinhtrang <> 'deleted'";
			$data_khuvucphutrach = $this->model_deliman_nhanvien->getPhuTrachKhuVucList($wherephutrach);
			$arr_nhanvienid = $this->string->matrixToArray($data_khuvucphutrach,"nhanvienphutrachid");
			$where .= " AND nhanvienid in ('".implode("','",$arr_nhanvienid)."')";
		}
		
		$this->data['datas'] = array();
		$where.=" AND trangthai <> 'deleted' ";
		$rows = $this->model_deliman_nhanvien->getList($where);
		//Page
		$page = $this->request->get['page'];		
		$x=$page;		
		$limit = 20;
		$total = count($rows); 
		// work out the pager values 
		$this->data['pager']  = $this->pager->pageLayout($total, $limit, $page); 
		
		$pager  = $this->pager->getPagerData($total, $limit, $page); 
		$offset = $pager->offset; 
		$limit  = $pager->limit; 
		$page   = $pager->page;
		for($i=$offset;$i < $offset + $limit && count($rows[$i])>0;$i++)
		//for($i=0; $i <= count($this->data['datas'])-1 ; $i++)
		{
			
			$this->data['datas'][$i] = $rows[$i];
			$this->data['datas'][$i]['link_edit'] = $this->url->http('deliman/nhanvien/update&nhanvienid='.$this->data['datas'][$i]['nhanvienid']);
			$this->data['datas'][$i]['text_edit'] = "Edit";
			$loainhanvien = $this->model_deliman_loainhanvien->getItem($this->data['datas'][$i]['loainhanvienid']);
			$this->data['datas'][$i]['tenloainhanvien'] = $loainhanvien['tenloainhanvien'];
			
			$where = " AND nhanvienphutrachid = '".$this->data['datas'][$i]['nhanvienid']."'";
			$where .= " AND tinhtrang <> 'deleted'";
			$data_khuvucphutrach = $this->model_deliman_nhanvien->getPhuTrachKhuVucList($where);
			$arr_khuvucid = $this->string->matrixToArray($data_khuvucphutrach,"khuvucid");
			$where = " AND khuvucid in ('". implode("','",$arr_khuvucid) ."')";
			$data_khuvuc = $this->model_deliman_khuvuc->getList($where);
			
			$arr_tenkhuvucphutrach = array();
			foreach($data_khuvuc as $khuvuc)
			{
				$arr_tenkhuvucphutrach[] = "<li>".$khuvuc['tenkhuvuc']." ".$khuvuc['tenphuongxa']." ".$khuvuc['tenquanhuyen']." ".$khuvuc['tentinhthanh']."</li>";
			}
			$this->data['datas'][$i]['khuvucphutrach'] = "<ul>".implode("",$arr_tenkhuvucphutrach)."</ul>";
		}
		$this->data['refres']=$_SERVER['QUERY_STRING'];
		$this->id='content';
		$this->template="deliman/nhanvien_list.tpl";
		$this->layout="layout/deliman";
		
		$this->render();
	}
	
	
	private function getForm()
	{
		//cb loai nhan vien
		$this->load->model('deliman/loainhanvien');
		$this->data['loainhanviens'] = $this->model_deliman_loainhanvien->getList();
		$this->data['khuvucphutrach'] = array();
		if ((isset($this->request->get['nhanvienid'])) ) 
		{
      		$this->data['item'] = $this->model_deliman_nhanvien->getItem($this->request->get['nhanvienid']);
			$where = " AND nhanvienphutrachid = '".$this->request->get['nhanvienid']."'";
			$where .= " AND tinhtrang <> 'deleted'";
			$this->data['khuvucphutrach'] = $this->model_deliman_nhanvien->getPhuTrachKhuVucList($where);	
    	}
		
		$this->id='content';
		$this->template='deliman/nhanvien_form.tpl';
		$this->layout="layout/deliman";
		
		$this->render();
	}
	
	public function save()
	{
		$this->load->model("deliman/loainhanvien");
		$data = $this->request->post;
		$loainhanvien = $this->model_deliman_loainhanvien->getItem($data['loainhanvienid']);
		$data['tenloainhanvien'] = $loainhanvien['tenloainhanvien'];
		if($this->validateForm($data))
		{
			
			
			if($data['nhanvienid']=="")
			{
				$data['nhanvienid'] = $this->model_deliman_nhanvien->insert($data);	
			}
			else
			{
				$this->model_deliman_nhanvien->update($data);	
			}
			//Tao tai khoan
			if($data['cotaikhoan']=='co')
			{
				$user['userid'] = $data['userid'];
				$user['username'] = $data['userid'];
				$user['usertypeid'] = 'nhanvien';
				$user['password'] = $data['password'];
				$user['fullname'] = $data['hoten'];
				$user['email'] = $data['email'];
				$user['status'] = 'active';
				$user['address'] = $data['diachi'];
				$user['phone'] = $data['dienthoai'];
				
				if($data['password']!="")
				{
					$this->model_core_user->insertUser($user);
					$this->model_core_user->updatestatus($user);
				}
				else
					$this->model_core_user->updateuser($user);
				$this->model_deliman_nhanvien->updateCol($data['nhanvienid'],'userid',$data['userid']);
				
				$this->model_core_user->updatestatus($user);
			}
			if($data['cotaikhoan']=='khong')
			{
				//Khóa tai khoang
				$nhanvien = $this->model_deliman_nhanvien->getItem($data['nhanvienid']);
				
				$user['userid'] = $nhanvien['userid'];
				$user['status'] = 'lock';
				$this->model_core_user->updatestatus($user);
			}	
			
			//Khu vuc phu trach
			//Xoa khu phu trach
			
			$listphutrachid = split(",",$data['khuvucdel']);
			//Neu ko phai la nhan vien quan ly khu vuc thi se bi xoa het cac khu dang phu trach
			if($data['loainhanvienid'] != '2')
			{
				//Lay cac khu vuc ma nhan vien do dang phu trach
				$where = " AND nhanvienphutrachid = '".$data['nhanvienid']."'";
				$phutrachkhuvucs = $this->model_deliman_nhanvien->getPhuTrachKhuVucList($where);
				
				$listphutrachid = $this->string->matrixToArray($phutrachkhuvucs,'id');
				
			}
			
			if(count($listphutrachid))
			{
				
				foreach($listphutrachid as $id)
				{
					if((int)$id!=0)
					{
						//$this->model_deliman_nhanvien->deletePhuTrachKhuVuc($id);
						$this->model_deliman_nhanvien->updatePhuTrachKhuVuc($id,'ngayketthuc',$this->date->getToday());
						$this->model_deliman_nhanvien->updatePhuTrachKhuVuc($id,'tinhtrang','deleted');
						//Remove nhanvienphutrachid ra table khuvuc
						$phutrachkhuvuc = $this->model_deliman_nhanvien->getPhuTrachKhuVuc($id);
						$this->model_deliman_khuvuc->updateCol($phutrachkhuvuc['khuvucid'],'nhanvienphutrachid','');
					}
				}
			}
			
			if($data['loainhanvienid'] == '2' || $data['loainhanvienid'] == '3')
			{
				
				//Luu khu vuc phu trach
				
				if(count($data['khuvuphutrach']))
					foreach($data['khuvuphutrach'] as $key => $khuvucid)
					{
						$dataphutrach['id'] = $data['id'][$key];
						$dataphutrach['nhanvienphancongid'] = $this->user->getNhanVien();
						$dataphutrach['khuvucid'] = $khuvucid;
						$dataphutrach['nhanvienphutrachid'] = $data['nhanvienid'];
						$dataphutrach['ngayphutrach'] = $this->date->getToday();
						
						$this->model_deliman_nhanvien->savePhuTrachKhuVuc($dataphutrach);
						//Gan nhanvienphutrachid -> khu vuc
						if($data['loainhanvienid'] == '2')
						{
				
							$this->model_deliman_khuvuc->updateCol($khuvucid,'nhanvienphutrachid',$data['nhanvienid']);
						}
					}
			}
			$this->data['output'] = "true";
		}
		else
		{
			foreach($this->error as $item)
			{
				$this->data['output'] .= $item."<br>";
			}
		}
		$this->id='content';
		$this->template='common/output.tpl';
		$this->render();
	}
	
	private function validateForm($data)
	{
	//	if (trim($data['manhanvien']) == "") 
//		{
//      		$this->error['manhanvien'] = "Bạn chưa nhập mã nhân viên";
//    	}
//		else
//		{
//			$where = "AND manhanvien = '".$data['manhanvien']."'";
//			$loaibaos = $this->model_deliman_nhanvien->getList($where);
//			if(count($loaibaos) > 0 && $data['nhanvienid'] == "")
//			{
//				$this->error['manhanvien'] = "Mã nhân viên đã tồn tại trong hệ thống";	
//			}
//		}
		
		if(trim($data['hoten']) == "") 
		{
      		$this->error['hoten'] = "Bạn chưa nhập tên nhân viên";
    	}
		if($data['cotaikhoan']=='co')
		{
			$nhanvien = $this->model_deliman_nhanvien->getItem($data['nhanvienid']);
			if($nhanvien['userid'] =="")
			{
				if($data['userid'] == "")
					$this->error['userid'] = "Bạn chưa nhập tên đăng nhập";
				else
				{	
					$where = " AND userid = '".$data['userid']."'";
					$users = $this->model_core_user->getList($where);
					if(count($users))
						$this->error['userid'] = "Tên đăng nhập đã được sử dụng";
					
				}
				if($data['password'] != "")
				{
					if($data['password'] != $data['confirmpassword'])
						$this->error['password'] = "Xác nhập mật khẩu không đúng";
				}
			}
		}
		//if (trim($data['tennhomnhanvien']) == "")
//		{
//			$this->error['tennhomnhanvien'] = "Bạn chưa nhập tên nhóm nhân viên";
//		}
	
		if (count($this->error)==0) {
	  		return TRUE;
		} else {
	  		return FALSE;
		}
	}
	//Cac ham xu ly tren form
	public function getTreeSelectView()
	{
		
		
		$root = @(int)$this->request->get['root'];
		$loainhanvienid = $this->request->get['loainhanvienid'];
		
		$this->data['output'] = $this->getTreeSelect($root,$loainhanvienid);
		$this->id='content';
		$this->template='common/output.tpl';
		$this->render();
	}
	
	private function getTreeSelect($root = 0,$loainhanvienid)
	{
		$khuvucs = $this->model_deliman_khuvuc->getChild($root);
		$str = "";
		foreach($khuvucs as $item)
		{
			$child = $this->model_deliman_khuvuc->getChild($item['khuvucid']);
			$str.='<li id="node'.$item['khuvucid'].'" class="closed" ref="'.$root.'">';
			$type = 'folder';
			if(count($child)==0)
			{
				$type = 'file';
			
			}
			$btnSelect = "";
			if($item['nhanvienphutrachid'] == 0 || $loainhanvienid == 3)
			{
				$btnSelect = '<a onClick="selectKhuVuc('.$item['khuvucid'].')">[Chọn]</a>';
			}
			$parent = '<input type="hidden" id="nodeparent_'.$item['khuvucid'].'" name="parent['.$item['khuvucid'].']" value="'.$root.'">';
			$nhavienphutrach = "";
			if($item['nhanvienphutrachid'])
				$nhavienphutrach = "(".$this->document->getNhanVien($item['nhanvienphutrachid'])." - ".$this->document->getNhanVien($item['nhanvienphutrachid'],"userid").")";
			$str.='<span id="khuvuc'.$item['khuvucid'].'" class="'.$type.'"><span id="tenkhuvuc'.$item['khuvucid'].'"><b>'.$item['tenkhuvuc'].'</b> '.$nhavienphutrach.'</span> '.$btnSelect.$parent.'</span>';
			if(count($child))
			{
				$str .= "<ul id='group".$item['khuvucid']."'>";
				$str .= $this->getTreeSelect($item['khuvucid'],$loainhanvienid);
				$str .= "</ul>";
			}
			$str.='</li>';
		}
		return $str;
	}
}
?>